<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { addArticleAPI, getCategoriesAPI, getArticleAPI } from '../apis/apis';

// 标签
const inputValue = ref('')
const dynamicTags = ref([])
const inputVisible = ref(false)
const InputRef = ref()
// 文章内容
const content = ref('')
// 文章标题
const title = ref('')
// 文章简介
const simple = ref('')
// 分类级联选择器 
const categoryName = ref([])
const customProps = ref({
  label: "name",
  value: "name"
})
// 分类列表
const options = ref([])
// 路由, 返回上一页
const router = useRouter()
// 路由, 获取文章id参数
const route = useRoute()
// 该页面是编辑模式还是预览模式
const mode = ref('preview')
// markdown组件
const preview = ref(null);

// 打开确认框, 提交文章数据
const open = () => {
  ElMessageBox.alert('确认提交吗', '提示', {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    callback: async (action) => {
      if (action === 'confirm') {
        if (!categoryName.value) {
          ElMessage({
            message: '请选择分类',
            type: 'warning',
            duration: '1000'
          })
          return
        }
        const articleInfo = {
          id: route.query.id ? route.query.id : '',
          title: title.value,
          simple: simple.value,
          content: content.value,
          category: options.value.find(item => item?.name === categoryName.value[0]),
          tags: dynamicTags.value
        }
        if (title.value == '' || simple.value == '' || content.value == '') {
          ElMessage({
            message: '请输入内容',
            type: 'warning',
          })
          return
        }
        const res = await addArticleAPI(articleInfo)
        if (res.code === 1) {
          ElMessage({
            message: '提交成功',
            type: 'success',
            duration: 1000
          })
        } else {
          ElMessage({
            message: '提交失败',
            type: 'error',
            duration: 1000
          })
        }
      }
    },
  })
}
// 获取分类
const getCategories = async () => {
  const res = await getCategoriesAPI()
  options.value = res.data
}

// 删除标签
const handleClose = (tag) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}
// 展示标签输入框
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value.input.focus()
  })
}
// 确认标签输入
const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push({
      id: null,
      name: inputValue.value,
      createTime: null
    })
  }
  inputVisible.value = false
  inputValue.value = ''
}
// 根据id获取文章信息
const getArticleInfo = async () => {
  const res = await getArticleAPI(route.query.id)
  title.value = res.data.title
  simple.value = res.data.simple
  content.value = res.data.content
  dynamicTags.value = res.data.tags
  categoryName.value[0] = res.data.category
}

// 切换编辑和预览模式, 需要改变url的query参数
const changeStatus = (status) => {
  mode.value = status
  router.push({
    query: { ...route.query, type: mode.value }
  })
}

onMounted(async() => {
  const isAdd = route.query.type
  mode.value = route.query.type
  // 获取分类列表
  getCategories()
  if (isAdd) {
    // 说明不是新增文章 获取文章信息
    await getArticleInfo()
  }
})

</script>

<template>

  <div class="px-5">
    <div class="flex items-center justify-center py-3  px-5">
      <div class="space-x-5">
        <el-button
          @click="router.back()"
          type="primary"
        >返回</el-button>
        <el-button
          :disabled="mode === 'preview'"
          @click="open"
          type="primary"
        >提交</el-button>
        <el-button type="primary">
          <div
            v-if="mode === 'preview'"
            @click="changeStatus('editable')"
          >
            编辑
          </div>
          <div
            v-else
            @click="changeStatus('preview')"
          >预览</div>
        </el-button>
      
      </div>

    </div>
    <div class="py-2 px-3 flex flex-col  space-y-2">
      <div class="flex items-center w-full space-x-3">
        <div class="flex items-center w-1/4">
          <div class="min-w-max text-gray-600 font-semibold px-2 text-xl">标题:</div>
          <el-input
            class="h-9"
            v-model="title"
            placeholder="标题"
            maxlength="15"
            show-word-limit
            :disabled="mode === 'preview'"
          />
        </div>
        <div class="w-1/5">
          <div class="px-2 flex min-h-fit min-w-max">
            <span class="flex min-w-max px-2 items-center">分类:</span>
            <el-cascader
              v-model="categoryName"
              :options="options"
              :props="customProps"
              :emitPath="false"
              :disabled="mode === 'preview'"
            >
              <template #default="{ node, data }">
                <span>{{ data?.name }}</span>
                <span v-if="!node.isLeaf"> {{ data.categoryList?.length }} </span>
              </template>
            </el-cascader>
          </div>
        </div>

        <div class="w-2/5">
          <div class="px-2 flex min-h-fit min-w-max">
            <span class="flex min-w-max px-2 items-center">标签:</span>

            <div class="flex gap-2">
              <el-tag
                v-for="tag in dynamicTags"
                :key="tag"
                :disable-transitions="false"
                :closable="mode === 'editable' || mode === undefined"
                @close="handleClose(tag)"
              >
                {{ tag?.name }}
              </el-tag>
              <el-input
                v-if="inputVisible"
                ref="InputRef"
                v-model="inputValue"
                class="w-20"
                size="small"
                @keyup.enter="handleInputConfirm"
                @blur="handleInputConfirm"
              />
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput"
                :disabled="mode === 'preview'"
              >
                + New Tag
              </el-button>
            </div>
          </div>
        </div>
        <div
          v-show="(content.length + simple.length) > 0"
          class="text-gray-500 text-md"
        >
          文章字数: {{ (content.length + simple.length) }}
        </div>
      </div>

      <div class="flex items-start w-full">
        <div class="min-w-max  text-gray-600 font-semibold px-2 text-xl">摘要:</div>
        <el-input
          class="h-20 z-10"
          v-model="simple"
          placeholder="文章摘要"
          show-word-limit
          maxlength="300"
          type="textarea"
          :rows="3"
          :disabled="mode === 'preview'"
        />
      </div>
    </div>
    <div class="flex min-h-full  pb-10 px-3">
      <v-md-editor
        :mode="mode"
        placeholder="请输入内容"
        v-model="content"
        autofocus
        ref="preview"
        height="50rem"
      >
      </v-md-editor>
    </div>
  </div>
</template>

<style
  scoped
  lang='scss'
></style>